package com.javacoo.xservice.base.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;

import com.javacoo.xservice.base.Constants;
import com.javacoo.xservice.base.setting.AppMaliciousRequestInterceptorSetting;
import com.javacoo.xservice.base.support.HttpCode;

import lombok.extern.slf4j.Slf4j;

/**
 * 恶意请求拦截器
 * <p>说明:</p>
 * <li></li>
 * @author DuanYong
 * @since 2017年2月7日下午4:29:45
 */
@Slf4j
public class MaliciousRequestInterceptor extends BaseInterceptor {
	@Autowired
	private AppMaliciousRequestInterceptorSetting appMaliciousRequestInterceptorSetting;
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        //如果关闭
        if(!appMaliciousRequestInterceptorSetting.getOpen()){
            return super.preHandle(request, response, handler);
        }
        HttpSession session = request.getSession();
        String preRequest = (String)session.getAttribute(Constants.PREREQUEST);
        Long preRequestTime = (Long)session.getAttribute(Constants.PREREQUEST_TIME);
        String url = request.getServletPath();
        //过滤频繁操作
        if (preRequestTime != null && preRequest != null) { 
        	//是否恶意
        	boolean malicious = System.currentTimeMillis() - preRequestTime < appMaliciousRequestInterceptorSetting.getMinRequestIntervalTime();
            if ((url.equals(preRequest) || appMaliciousRequestInterceptorSetting.getAllRequest())
                && malicious) {
                Integer maliciousRequestTimes = (Integer)session.getAttribute(Constants.MALICIOUS_REQUEST_TIMES);
                if (maliciousRequestTimes == null) {
                    maliciousRequestTimes = 1;
                } else {
                    maliciousRequestTimes++;
                }
                session.setAttribute(Constants.MALICIOUS_REQUEST_TIMES, maliciousRequestTimes);
                if (maliciousRequestTimes > appMaliciousRequestInterceptorSetting.getMaxMaliciousTimes()) {
                    response.setStatus(HttpCode.MULTI_STATUS.value());
                    log.warn("拦截到恶意请求 : {}", url);
                    return false;
                }
            } else {
                session.setAttribute(Constants.MALICIOUS_REQUEST_TIMES, 0);
            }
        }
        session.setAttribute(Constants.PREREQUEST, url);
        session.setAttribute(Constants.PREREQUEST_TIME, System.currentTimeMillis());
        return super.preHandle(request, response, handler);
    }
}
